package com.ayuku.commons;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import net.sf.persist.Persist;

public class SqliteDB {
	private static Connection conn;
	private static Properties props;
	private static String jdbcString;
	private static int n = 0;
	private static Persist prsist;

	public static void openDB() throws InstantiationException,
			IllegalAccessException, ClassNotFoundException,
			FileNotFoundException, IOException, SQLException {
		Class.forName("org.sqlite.JDBC").newInstance();
		setProp(); 
		prsist = new Persist(getConn());
	}

	private static void setProp() throws FileNotFoundException, IOException {
		jdbcString = "jdbc:sqlite:./db/course.db";
		props = new Properties();
		props.put("user", "");
		props.put("password", "");
	}

	public static Connection getConn() throws SQLException {
		if (conn == null || conn.isClosed()) {
			conn = DriverManager.getConnection(jdbcString, props);
			n += 1;
			System.out.println("connect lagi*** " + n);
		}
		conn.setAutoCommit(true);
		return conn;
	}

	public static void closeConn() throws java.sql.SQLException {
		if (conn!=null){
			conn.close();
		}
	}

	public static Persist getPersist() throws SQLException {
		if (prsist == null || prsist.getConnection() == null
				|| prsist.getConnection().isClosed() || conn.isClosed()) {
			prsist = new Persist(getConn());
		}
		return prsist;
	}

}
